package com.zengfa.task.api.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JobUtil {

	public static String getLocalIp() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostAddress();
		} catch (UnknownHostException e) {
			log.error("获取服务器本地IP异常", e);
		}
		return null;
	}
	
	private static Map<String,ThreadPoolTaskExecutor> executorMap = new ConcurrentHashMap<>();
	public static synchronized ThreadPoolTaskExecutor getTaskExecutor(String jobGroup) {
		ThreadPoolTaskExecutor executor = executorMap.get(jobGroup);
		if(executor != null) {
			return executor;
		}
		executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(100);
        //配置最大线程数
        executor.setMaxPoolSize(200);
        //配置队列大小
        executor.setQueueCapacity(50);
//        executor.setAllowCoreThreadTimeOut(true);
        // 线程空闲后的最大存活时间 60s
        executor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(jobGroup+"_");
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // AbortPolicy：丢弃任务并抛出RejectedExecutionException异常。 默认策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //执行初始化
        executor.initialize();
        executorMap.put(jobGroup, executor);
        return executor;
	}
	
}
